package moe.oil.db.api;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import moe.oil.db.service.SchoolService;
import moe.oil.dto.school.SchoolDTO;
import moe.oil.exception.school.SchoolIdNotFoundException;
import moe.oil.exception.school.SchoolNameNullException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/15 21:56
 * Description:
 *
 * @author - -
 */
@RestController
@Slf4j
@Setter(onMethod_ = @Autowired)
@RequestMapping("/school")
@CrossOrigin
public class SchoolController {
    private SchoolService schoolService;

    // 添加学校
    @PostMapping
    public SchoolDTO addSchool(@Validated @RequestBody SchoolDTO schoolDTO) {
        return schoolService.save(schoolDTO);
    }

    // 查询全部学校
    @GetMapping("/{page}/{size}")
    public List<SchoolDTO> getAllSchool(@PathVariable("page") int page,@PathVariable("size") int size) {
        return schoolService.findAll(PageRequest.of(page, size));
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public SchoolDTO findById(@PathVariable("id") Long schoolId) {
        if (schoolId != null && schoolId != 0) {
            return schoolService.findBySchoolId(schoolId);
        } else {
            throw new SchoolIdNotFoundException(schoolId);
        }
    }

    // 根据Name查询学校
    @GetMapping("/query")
    public SchoolDTO findBySchoolName(@RequestBody SchoolDTO schoolDTO) {
        var name= schoolDTO.getSchoolName();
        if (name != null && !name.equals(" ")) {
            return schoolService.findBySchoolName(name);
        } else {
            throw new SchoolNameNullException(name);
        }
    }

    // 修改学校
    @PutMapping
    public SchoolDTO updateSchool(@Validated @RequestBody SchoolDTO schoolDTO) {
        if (schoolDTO.getSchoolId() != null && schoolDTO.getSchoolId() != 0) {
            return schoolService.update(schoolDTO);
        } else {
            throw new SchoolIdNotFoundException(schoolDTO.getSchoolId());
        }
    }

    // 根据ID删除学校
    @DeleteMapping("/{id}")
    public int deleteSchool(@PathVariable("id") Long schoolId) {
        return schoolService.delete(schoolId);
    }
}

